package com.yc.qunxing.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yc.qunxing.entity.Admins;
import com.yc.qunxing.entity.Users;
import com.yc.qunxing.properties.JwtProperties;
import com.yc.qunxing.result.Result;
import com.yc.qunxing.service.IAdminsService;
import com.yc.qunxing.service.IUsersService;
import com.yc.qunxing.utils.AppJwtUtil;
import com.yc.qunxing.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 鹏哥
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/admins")
@Slf4j
public class AdminController {


    @Autowired
    private IAdminsService iAdminsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result<Admins> LoginedAdmin(HttpServletRequest req, HttpServletResponse resp,@RequestBody Admins admins) throws IOException {
        // 从请求体中获取手机号和密码
        String phoneNumber = admins.getPhoneNumber();
        String password = admins.getPassword();
        String verification = admins.getVerification();
        int t=doPics(req,resp,verification);
        if(t==0){
            return Result.error("验证码错误");
        }
        // 构建查询条件
        QueryWrapper<Admins> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", phoneNumber).eq("password", password);

        // 根据手机号和密码查询用户信息
        Admins admin = iAdminsService.getOne(queryWrapper);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", admin.getId());
        String token = JwtUtil.createJWT(
                JwtProperties.adminSecretKey,
                JwtProperties.adminTtl,
                claims);
/*        String token = AppJwtUtil.getToken(admin.getId().longValue());*/
        admin.setToken(token);
        if (admin != null) {
            // 登录成功
            return Result.success(admin);
        } else {
            // 登录失败
            return Result.error("手机号或密码错误");
        }
    }
    protected int doPics(HttpServletRequest req, HttpServletResponse resp, String usafe) throws IOException {
        HttpSession session=req.getSession();
        String sessionId = session.getId();
        /*String scpat = (String) session.getAttribute("verityCode");*/
        String scpat = (String) redisTemplate.opsForValue().get(sessionId);
        System.out.println("who:"+usafe+","+scpat);
        if(scpat != null && scpat.equals(usafe)){
            return 1;
        }else{
            return 0;
        }
    }
}
